<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    // 保存
    public function save(Request $request) {
        // 保存时检查用户名是否已经存在
        if (User::query()->where('username', $request->get('username'))->first()) {
            return response()->json(['code' => '400', 'msg' => '用户名已存在']);
        }
        // 插入或更新
        $data = $request->all();
        $user = User::query()->find($request->get('id'));
        if ($user) {
            $user->update($data);
            return response()->json(['code' => '200', 'msg' => '更新成功']);
        }
        User::query()->create($data);
        return response()->json(['code' => '200', 'msg' => '插入成功']);
    }

    // 删除（根据ID）
    public function delete(Request $request) {
        $id = $request->get('id');
        User::destroy($id);
        return response()->json(['code' => '200', 'msg' => '删除成功']);
    }

    // 查询全部
    public function list() {
        $res = User::query()->get();
        return response()->json(['code' => '200', 'msg' => '获取成功', 'data' => $res]);
    }

    // 查询单个（根据ID）
    public function one(Request $request) {
        $res = User::query()->find($request->get('id'));
        return response()->json(['code' => '200', 'msg' => '获取成功', 'data' => $res]);
    }

    // 登录
    public function login(Request $request) {
        $username = $request->get('username');
        $password = $request->get('password');
        $res = User::query()->where('username', $username)->where('password',  $password)->first();
        if ($res) {
            return response()->json(['code' => '200', 'msg' => '登录成功', 'data' => $res]);
        } else {
            return response()->json(['code' => '400', 'msg' => '用户名或密码错误']);
        }
    }

    // 注册
    public function register(Request $request) {
        // 注册时检查用户名是否已经存在
        if (User::query()->where('username', $request->get('username'))->first()) {
            return response()->json(['code' => '400', 'msg' => '用户名已存在']);
        }
        $data = $request->all();
        $res = User::query()->create($data);
        return response()->json(['code' => '200', 'msg' => '注册成功', 'data' => $res]);
    }

    // 检查用户名
    public function checkUsername(Request $request) {
        // 注册时检查用户名是否已经存在
        if (User::query()->where('username', $request->get('username'))->first()) {
            return response()->json(['code' => '400', 'msg' => '用户名已存在']);
        }
        return response()->json(['code' => '200', 'msg' => '用户名可用']);
    }

}
